<template>
  <el-container>
    <el-aside width="200px">
      <CompanyMenu></CompanyMenu>
    </el-aside>

    <el-form :model="department" :rules="rules" ref="department" label-width="100px" class="demo-ruleForm" style="margin-top:30px">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="department.name"></el-input>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input type="sort" v-model.number="department.sort" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm()">立即创建</el-button>
        <el-button @click="resetForm('department')">重置</el-button>
      </el-form-item>
    </el-form>
    <el-button type="text"></el-button>
  </el-container>
</template>

<script>
import CompanyMenu from '@/components/menu/CompanyMenu.vue'
import instanceToken from '@/utlis/tokenIdentify.js'

export default {
  name: 'AddView',
  components: {
    CompanyMenu
  },
  data() {
    var validataDepartmentName = (rule, value, callback) => {
      if (!value) {
        callback(new Error("部门名称不能为空"))

      } else {
        callback()
      }
    };
    var validataDepartmentSort = (rule, value, callback) => {
      if (!value) {
        callback(new Error("排序不能为空"));
      }
      var str = value;
      var re = /\d+/;
      if (!re.test(str)) {
        callback(new Error("只能为数字"))
      } else {
        callback()
      }
    };
    return {
      department: {
        name: '',
        sort: '',
        companyId: ''
      },
      rules: {
        name: [{
          validator: validataDepartmentName,
          trigger: 'blur'
        }],
        sort: [{
          validator: validataDepartmentSort,
          trigger: 'blur'
        }]
      },
    };
  },
  created: function () {},
  methods: {
    submitForm() {
      this.$refs.department.validate(valid => {
        if (valid) {
          var loginUser = window.sessionStorage.getItem("loginUser");
          var userinfo = JSON.parse(loginUser);
          this.department.companyId = userinfo.id;
          instanceToken.post("/department/leader/add", this.department).then(res => {
            this.department = "";
          });
          this.$alert('添加成功', '新增部门', {
            confirmButtonText: '确定',
          });

        } else {
          this.department = {};
          this.$alert('添加失败,请重新检查输入内容', '新增部门', {
            confirmButtonText: '确定',
          });
          return false
        }
      })

      this.$refs.department.clearValidate();
    },
  },

}
</script>
